﻿// **********************************************************************
//
// Author: KingSley
// Email:3268374537@qq.com
// Created:	2018/8/1   09:55
// Introduce: 摄像机的控制方式，第一人称可控摄像机
//
// **********************************************************************
using UnityEngine;

namespace KingSley
{
    [AddComponentMenu("KingARPG/摄像机/第一人称按键控制摄像机")]
    /// <summary>
    /// 通过鼠标的按键Q、E、R、T控制摄像机
    /// </summary>
    public class CameraInTheFirstPerson : MonoSingleton<CameraInTheFirstPerson>
    {
        /// <summary>
        /// 观察目标
        /// </summary>
        public Transform Target;
        /// <summary>
        /// 限定观察距离
        /// </summary>
        public float Distance = 10.0F;
        /// <summary>
        /// X轴和Y轴的旋转速度
        /// </summary>
        private float SpeedX = 30;
        private float SpeedY = 30;
        /// <summary>
        /// 角度限制
        /// </summary>
        private float MinLimit_Y = 30;
        private float MaxLimit_Y = 180;
        /// <summary>
        /// 旋转角度e
        /// </summary>
        private float mX = 0.0F;
        private float mY = 0.0F;
        /// <summary>
        /// 经计算后，旋转到的角度，以便平滑旋转
        /// </summary>
        private Quaternion CRotation;
        private Vector3 CPosition;
        /// <summary>
        /// 位置临时存储变量
        /// </summary>
        private Transform Temp_transform;

        void Awake()
        {
            Temp_transform = transform;
        }

        void Start()
        {
            // 初始化旋转角度
            mX = transform.eulerAngles.x;
            mY = transform.eulerAngles.y;
        }
        void LateUpdate()
        {
            if (Target != null)
            {
                if (Input.GetKey(KeyCode.E))
                {
                    transform.RotateAround(this.transform.position, -1 * Vector3.up, SpeedX * Time.deltaTime);
                }
                else if (Input.GetKey(KeyCode.Q))
                {
                    transform.RotateAround(this.transform.position, Vector3.up, SpeedX * Time.deltaTime);
                }
                if (Input.GetKey(KeyCode.R))
                {

                    transform.RotateAround(this.transform.position, transform.right, SpeedY * Time.deltaTime);
                }
                else if (Input.GetKey(KeyCode.T))
                {

                    transform.RotateAround(this.transform.position, -1 * transform.right, SpeedY * Time.deltaTime);
                }

                CRotation = this.transform.rotation;
                // 重新计算位置
                CPosition = new Vector3(0.0F, 0.0F, -Distance * CPosition.z) + Target.transform.position;
                transform.position = CPosition;
            }
        }
    }
}
